package com.suxin.plugin.loader;

import com.suxin.plugin.loader.load.PluginClassLoader;
import com.suxin.plugin.pf4j.BasePlugin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Tang
 * @classname PluginResourceLoadFactory
 * @description [  ]
 * @date 2022/7/21 22:18
 */
public class PluginResourceLoadFactory {

    private final List<PluginResourceLoader> pluginResourceLoaders = new ArrayList<>();
    private final Map<String, ResourceWrapper> resourceWrapperMap = new HashMap<>();

    public PluginResourceLoadFactory() {
        this.pluginResourceLoaders.add(new PluginClassLoader());
    }

    /**
     * 加载类文件
     * @param basePlugin
     */
    public synchronized void load(BasePlugin basePlugin) {
        for (PluginResourceLoader resourceLoader : pluginResourceLoaders) {
            if (resourceLoader == null) {
                continue;
            }
            try {
                resourceWrapperMap.put(resourceLoader.key(), resourceLoader.load(basePlugin));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * unLoad
     * @param basePlugin
     */
    public synchronized void unLoad(BasePlugin basePlugin) {
        for (PluginResourceLoader resourceLoader : pluginResourceLoaders) {
            if (resourceLoader == null) {
                continue;
            }
            try {
                resourceLoader.unload(basePlugin,resourceWrapperMap.get(resourceLoader.key()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public ResourceWrapper getResourceWrapper(String key) {
        return resourceWrapperMap.get(key);
    }

}
